package com.zib.vread.greendaodemo;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.dao.query.Query;

public class MainActivity extends AppCompatActivity {
    @Bind(R.id.name)
    EditText name;
    @Bind(R.id.age)
    EditText age;
    @Bind(R.id.db)
    TextView db_text;
    private SQLiteDatabase db;
    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private Cursor cursor;
    private SimpleCursorAdapter adapter;
    private PersonDao dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "persons-db", null);
        db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        dao = daoSession.getPersonDao();
    }

    public void clickButton(View view) {
        switch (view.getId()){
            case R.id.button_save:
                String name_string = name.getText().toString().trim();
                int age_int = Integer.parseInt(age.getText().toString().trim());
                Person person = new Person(null, name_string, age_int, age_int + "");
                Log.e("tag", "name-->" + person.getName() + "---" + "age---->" + person.getAge());
                dao.insert(person);
                break;
            case R.id.button_load:
                Query<Person> query = dao.queryBuilder().build();
                List<Person> persons = query.list();
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i <persons.size(); i++) {
                    builder.append(persons.get(i).getName());
                    builder.append(persons.get(i).getAge());
                }
                db_text.setText(builder.toString());
                break;
        }
    }
}
